package com.cn.zengzeng.spbzengzeng.utils;

import kotlin.text.Charsets;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;

/**
 * 发邮件工具类
 *
 * 成功开启POP3/SMTP服务,在第三方客户端登录时，密码框请输入以下授权码：

 wcseztbkrelobehb
 */
@Slf4j
public final class MailUtils {
    /**
     * 发件人账号，同邮箱地址
     */
    private static final String USER = "stx136@foxmail.com";
    /**
     * 如果是qq邮箱/其他邮箱等可以使户端授权码，或者登录密码
     */
    private static final String PASSWORD = "uzfmmxixupmnechg";

    /**
     * 协议
     */
    private static final String PROTOCOL = "smtp";

    /**
     *协议 是否需要SMTP验证
     */
    private static final String MAIL_AUTH = "true";
    /**
     * 协议地址
     */
    private static final String MAIL_HOST = "smtp.qq.com";

    /**
     * 发件人账号字段
     */
    private static final String MAIL_ACCOUNT_CONDITION = "mail.user";
    /**
     * 邮箱协议地址字段
     */
    private static final String MAIL_PROTOCOL_ADDRESS_CONDITION = "mail.smtp.host";
    /**
     * 邮箱协议地址字段 AUTH
     */
    private static final String MAIL_PROTOCOL_AUTH_CONDITION = "mail.smtp.auth";
    /**
     * 邮箱密码字段
     */
    private static final String MAIL_ACCOUNT_PASSWORD_CONDITION = "mail.smtp.password";


    /**
     *
     * @param to 收件人邮箱
     * @param text 邮件正文
     * @param title 标题
     */
    /* 发送验证信息的邮件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put(MAIL_PROTOCOL_AUTH_CONDITION, MAIL_AUTH);
            props.put(MAIL_PROTOCOL_ADDRESS_CONDITION, MAIL_HOST);

            // 发件人的账号
            props.put(MAIL_ACCOUNT_CONDITION, USER);
            //发件人的密码
            props.put(MAIL_ACCOUNT_PASSWORD_CONDITION, PASSWORD);

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty(MAIL_ACCOUNT_CONDITION);
                    String password = props.getProperty(MAIL_ACCOUNT_PASSWORD_CONDITION);
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty(MAIL_ACCOUNT_CONDITION);
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);

            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    public static String getMailHtml(String account){
        String url = "http://localhost:8090/active";
        return  "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "\t<meta charset=\"UTF-8\">\n" +
                "\t<title>激活账号邮件</title>\n" + "</head>\n" + "<body>\n" + "\t<h1>尊敬的用户，您好！</h1>" +
                "\n" + "\t<p>感谢您注册我们的网站。请点击下面的链接激活您的账号：</p>\n" +
                "\t<a href="+url+">"+url+"</a>\n" + "\t<p>该链接将在10分钟后过期，请尽快激活您的账号。" +
                "</p>\n" + "\t<font face=\"'Nunito', sans-serif\" color=\"#585858\" style=\"font-size: 24px; line-height: 32px;\">\n" + "       " +
                "               <span style=\"font-family: 'Nunito', Arial, Tahoma, Geneva," +
                " sans-serif; color: #aaaaaa; font-size: 16px; line-height: 32px;\">(如果您从未请求发送邮箱验证码，请忽略此邮件)</span>\n" + "         " +
                "           </font>\n" + "\t<p>祝您使用愉快！</p>\n" + "</body>\n" + "</html>";
    }
    public static String getForgetPassMailHtml(String verification){
        return "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "\t<meta charset=\"UTF-8\">\n" +
                "\t<title>忘记密码</title>\n" + "</head>\n" + "<body>\n" + "\t<h1>尊敬的用户，您好！</h1>\n" +
                "\t<p>感谢您使用我们的网站。以下是验证码，将在十分钟后过期：</p>\n" + "\t\t<div class=\"code-container\">\n"
                + "\t\t  <span class=\"code-number\">"+verification+"</span>\n" + "\t\t</div>\n" +
                "\t<font face=\"'Nunito', sans-serif\" color=\"#585858\" style=\"font-size: 24px; line-height: 32px;\">\n" +
                "\t\t<span style=\"font-family: 'Nunito', Arial, Tahoma, Geneva, sans-serif; " +
                "color: #aaaaaa; font-size: 16px; line-height: 32px;\">(如果您从未请求发送邮箱验证码，请忽略此邮件)</span>\n" + "   " +
                "  </font>\n" + "\t<p>祝您使用愉快！</p>\n" + "\t\n" + "</body>\n" + "<style>\n" +
                ".code-container {\n" + "  display: inline-block;\n" + "  padding: 5px;\n" + "  border: 1px solid #ccc;\n" +
                "  border-radius: 3px;\n" + "  font-size: 20px;\n" + "}\n" + "\n" + "/* 验证码数字的样式 */\n" + ".code-number" +
                " {\n" + "  display: inline-block;\n" + "  margin: 0 5px;\n" + "  font-weight: bold;\n" + "  color: #333;\n" + " " +
                " text-align: center;\n" + "  line-height: 1.2;\n" + "  font-family: Arial, sans-serif;\n" + "}\n" + "</style>\n" + "</html>";
    }
   /*
   *
   * 发送邮件带附件图片
   * */
    @Test
    public void sendMail() throws UnsupportedEncodingException, MessagingException {
        //1.创建邮件对象
        Properties properties = new Properties();
        // 指定SMTP服务器
        properties.put(MAIL_PROTOCOL_ADDRESS_CONDITION, MAIL_HOST);
        // 指定是否需要SMTP验证
        properties.put(MAIL_PROTOCOL_AUTH_CONDITION, MAIL_AUTH);
        Session session = Session.getInstance(properties);
        MimeMessage message =new MimeMessage(session);

        /*2.设置发件人
         * 其中 InternetAddress 的三个参数分别为: 邮箱, 显示的昵称(只用于显示, 没有特别的要求), 昵称的字符集编码
         * */
        message.setFrom(new InternetAddress(MailUtils.USER,"zengzeng",StandardCharsets.UTF_8.name()));
        /*3.设置收件人
        To收件人   CC 抄送  BCC密送*/
        message.setRecipient(Message.RecipientType.TO,new InternetAddress("a13619206145@163.com","xiuhong","UTF-8"));

        /*4.设置标题*/
        message.setSubject("测试邮件","UTF-8");

        /*5.设置邮件正文*/
        //一个Multipart对象包含一个或多个bodypart对象，组成邮件正文
        MimeMultipart multipart = new MimeMultipart();
        //读取本地图片,将图片数据添加到"节点"
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dataHandler1 = new DataHandler(new FileDataSource("D:\\bizhiJpg\\7.jpg"));
        image.setDataHandler(dataHandler1);
        image.setContentID("image_suo");
      //  D:\bizhiJpg\7.jpg
        //创建文本节点
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("这张图片<br/><img src='cid:image_suo'/>","text/html;charset=UTF-8");

        //创建附件节点  读取本地文件,并读取附件名称
        MimeBodyPart file1 = new MimeBodyPart();
        DataHandler dataHandler2 = new DataHandler(new FileDataSource("D:\\bizhiJpg\\7.jpg"));
        file1.setDataHandler(dataHandler2);
        file1.setFileName(MimeUtility.encodeText(dataHandler2.getName()));

        MimeBodyPart file2 = new MimeBodyPart();
        DataHandler dataHandler3 = new DataHandler(new FileDataSource("C:\\Users\\zengzeng\\Desktop\\新建 XLSX 工作表 (3).xlsx"));
        file2.setDataHandler(dataHandler3);
        file2.setFileName(MimeUtility.encodeText(dataHandler3.getName()));

        //将文本和图片添加到multipart
        multipart.addBodyPart(text);
        multipart.addBodyPart(image);
        multipart.addBodyPart(file1);
        multipart.addBodyPart(file2);
        multipart.setSubType("mixed");//混合关系

        message.setContent(multipart);

        message.setSentDate(new Date());
        message.saveChanges();
        Transport transport = session.getTransport(PROTOCOL);
        transport.connect(MAIL_HOST,MailUtils.USER,MailUtils.PASSWORD);
        transport.sendMessage(message,message.getAllRecipients());
        transport.close();
        log.info(Calendar.getInstance().getTime()+" : # Send mail to "+" success #");
    }

}
